package zyf;

public class SyncDemo extends Thread{


    public static void main(String[] args) {
        class Table{
            private  int beans = 20;
            public synchronized int  getBean(){  //同步方法
                if (beans==0){
                    throw  new RuntimeException("没有豆子了");
                }


                Thread.yield();
                return beans--;
            }

        }
        Table table=new Table();
        Thread t1 = new Thread(){
            @Override
            public void run(){
                while (true) {
                    int bean = table.getBean();
                    Thread.yield();
                    System.out.println(Thread.currentThread().getName()+bean);

                }
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run(){
                while (true) {
                    int bean = table.getBean();
                    Thread.yield();
                    System.out.println(Thread.currentThread().getName()+bean);

                }
            }
        };
        t1.setName("线程一");
        t2.setName("线程二");
        t1.start();
        t2.start();

    }
}
